module builder.Skeleton;
import frontend.Types;
import loader.scene.format.Hme;
import loader.scene.Node;
static import loader.scene.Animation;
import utils.Memory;
import maths.Vec;
import maths.Quat;
import maths.CoordSys;

Skeleton loadSkeleton(char[] filename, char[] modelname){
	Skeleton skeleton= getSkeleton();
	HmeLoader hml;
	loader.scene.Animation.SkeletalAnimation skelAnim;
	Bone[] bones;
	hml= new HmeLoader;
	hml.load(filename);
	assert(hml !is null);
	
	
	foreach(node; hml.scene.nodes){
		if(node.name!=modelname) continue;
		skelAnim = cast(loader.scene.Animation.SkeletalAnimation)node.animation;
		bones = new Bone[skelAnim.bones.length];
		foreach(index, inout bone;bones){
			bone.setIndex(index);
		}
		
		foreach(index, bone; skelAnim.bones){
			if(bone.parentId==-1)
				skeleton.pelvis=&bones[index];
			else if(bone.parentId>=0){
				bones[bone.parentId].addChild(&bones[index]);
				bones[index].setParent(&bones[bone.parentId]);
			} else assert(false);
		}
		
		skeleton.bones=bones;
		skeleton.rotandtrans.alloc(skeleton.bones.length);
		skeleton.rotonly.alloc(skeleton.bones.length);
		skeleton.firsts.alloc(skeleton.bones.length);
		
		break;
	}

	foreach(node; hml.scene.nodes){
		if(node.name!=`Bip01`) continue;
		skeleton.coordSys=node.coordSys;
		break;
	}
	return skeleton;
}


Skeleton loadSkeleton(HmeLoader hml, char[] modelname){
	Skeleton skeleton= getSkeleton();
	loader.scene.Animation.SkeletalAnimation skelAnim;
	Bone[] bones;
	assert(hml !is null);
	
	foreach(node; hml.scene.nodes){
		if(node.name!=modelname) continue;
		skelAnim = cast(loader.scene.Animation.SkeletalAnimation)node.animation;
		bones = new Bone[skelAnim.bones.length];
		foreach(index, inout bone;bones){
			bone.setIndex(index);
		}
		
		foreach(index, bone; skelAnim.bones){
			if(bone.parentId==-1)
				skeleton.pelvis=&bones[index];
			else if(bone.parentId>=0){
				bones[bone.parentId].addChild(&bones[index]);
				bones[index].setParent(&bones[bone.parentId]);
			} else assert(false);
		}
		
		skeleton.bones=bones;
		skeleton.rotandtrans.alloc(skeleton.bones.length);
		skeleton.rotonly.alloc(skeleton.bones.length);
		skeleton.firsts.alloc(skeleton.bones.length);
		
		break;
	}
	
	foreach(node; hml.scene.nodes){
		if(node.name!=`Bip01`) continue;
		skeleton.coordSys=node.coordSys;
		break;
	}
		
	return skeleton;
}

